import subprocess
import os

def execute_code(code):
    try:
        if not os.path.exists("TempApp"):
            subprocess.run(["dotnet", "new", "console", "-o", "TempApp", "--force"], check=True)

        with open("TempApp/Program.cs", "w", encoding='utf-8') as file:
            file.write(code)

        # 实时读取输出，避免缓冲区阻塞
        process = subprocess.Popen(
            ["dotnet", "run", "--project", "TempApp"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding='utf-8'
        )

        # 实时输出
        for line in process.stdout:
            print(line.strip())

        process.wait()

    except subprocess.CalledProcessError as e:
        print(f"执行时发生错误: {e}")
